﻿using dz.loger.core;
using System.Text;


namespace dz.util.core
{
    /// <summary>
    /// http请求工具类
    /// </summary>
    public class HttpUtil
    {
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public async Task<WebResult> Post(string url, string data)
        {
            return await Post(url, data, "application/json");
        }
        public async Task<WebResult> Post(string url, string data,string mediaType)
        {
            Dictionary<string, string> header = new Dictionary<string, string>();

            return await Post(url, data, header, mediaType);
        }


        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public async Task<WebResult> Post(string url, string data, Dictionary<string, string> header)
        {

            return await Post(url, data, header, "application/json");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="header"></param>
        /// <param name="mediaType">application/x-www-form-urlencoded
        /// application/json</param>
        /// <returns></returns>
        //public async Task<WebResult> Post(string url, string data, Dictionary<string, string> header, string mediaType= "application/json")
        //{

        //    WebResult result = new WebResult();

        //    try
        //    {
        //        HttpClient client = HttpService.Instance.HttpClientFactory.CreateClient("DefaultClient");

        //        client.Timeout = TimeSpan.FromSeconds(30);

        //        var content = new StringContent(data, Encoding.UTF8, mediaType);
        //        var request = new HttpRequestMessage(HttpMethod.Post, url)
        //        {
        //            Content = content
        //        };

        //        if (header != null)
        //        {
        //            foreach (var item in header)
        //            {
        //                request.Headers.Add(item.Key, item.Value);
        //            }
        //        }


        //        var response = await client.SendAsync(request).ConfigureAwait(false);
        //        response.EnsureSuccessStatusCode();
        //        string msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);


        //        result.Sucess = true;
        //        result.Data = msg;
        //    }
        //    catch (Exception ex)
        //    {
        //        LogUtil.Instance.Error(ex.Message);
        //        LogUtil.Instance.Error(ex.StackTrace);
        //        LogUtil.Instance.Error($"url:{url},data{data}");
        //        result.Data = ex.Message;
        //    }

        //    return result;
        //}

        public async Task<WebResult> Post(string url, string data, Dictionary<string, string> header, string mediaType = "application/json")
        {
            WebResult result = new WebResult();
            const int maxRetries = 3;
            int retryCount = 0;

            while (retryCount < maxRetries)
            {
                try
                {
                    // 使用命名客户端而不是默认客户端
                    HttpClient client = HttpService.Instance.HttpClientFactory.CreateClient("DefaultClient");

                    // 设置合理的超时时间
                    client.Timeout = TimeSpan.FromSeconds(120);

                    var content = new StringContent(data, Encoding.UTF8, mediaType);
                    var request = new HttpRequestMessage(HttpMethod.Post, url)
                    {
                        Content = content
                    };

                    if (header != null)
                    {
                        foreach (var item in header)
                        {
                            request.Headers.Add(item.Key, item.Value);
                        }
                    }

                    var response = await client.SendAsync(request).ConfigureAwait(false);

                    if ((int)response.StatusCode >= 500) // 服务器错误，可以重试
                    {
                        retryCount++;
                        if (retryCount < maxRetries)
                        {
                            await Task.Delay(1000 * retryCount); // 指数退避
                            continue;
                        }
                    }

                    response.EnsureSuccessStatusCode();
                    string msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result.Sucess = true;
                    result.Data = msg;
                    return result;
                }
                catch (HttpRequestException ex) when (retryCount < maxRetries)
                {
                    retryCount++;
                    LogUtil.Instance.Debug($"请求失败，第{retryCount}次重试。错误: {ex.Message}");

                    if (retryCount < maxRetries)
                    {
                        await Task.Delay(1000 * retryCount);
                    }
                    else
                    {
                        LogUtil.Instance.Error($"最终请求失败: {ex.Message}");
                        LogUtil.Instance.Error(ex.StackTrace);
                        LogUtil.Instance.Error($"url:{url}, data:{data}");
                        result.Data = ex.Message;
                    }
                }
                catch (Exception ex)
                {
                    LogUtil.Instance.Error(ex.Message);
                    LogUtil.Instance.Error(ex.StackTrace);
                    LogUtil.Instance.Error($"url:{url}, data:{data}");
                    result.Data = ex.Message;
                    return result;
                }
            }

            return result;
        }

        public async Task<WebResult> Get(string url, FormUrlEncodedContent content)
        {
            WebResult result = new WebResult();
            try
            {
                HttpClient client = HttpService.Instance.HttpClientFactory.CreateClient("DefaultClient");

                client.Timeout = TimeSpan.FromSeconds(180);

                string urlWithQuery = $"{url}?{content.ReadAsStringAsync().Result}";


                using (var request = new HttpRequestMessage(HttpMethod.Get, urlWithQuery))
                {


                    // 发送GET请求
                    HttpResponseMessage response = await client.SendAsync(request);

                    // 确保响应状态为成功
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();

                    LogUtil.Instance.Debug(responseBody);

                    result.Sucess = true;
                    result.Data = responseBody;
                }
            }
            catch (Exception ex)
            {
                LogUtil.Instance.Error(ex.Message);
                LogUtil.Instance.Error(ex.StackTrace);
                result.Data = ex.Message;
            }

            return result;
        }

    }
}
